package megrez.mail.sender.config;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import lombok.extern.slf4j.Slf4j;
import megrez.mail.sender.common.ErrorResponse;
import megrez.mail.sender.common.MailSenderException;
import megrez.mail.sender.utils.ContentNotFoundException;
import megrez.mail.sender.utils.TemplateNotFoundException;

/**
 * 统一异常处理
 *  
 * @author Lucky Yang
 * @since 2.6.9
 */
@RestControllerAdvice
@Slf4j
public class ControllerExceptionHandler {
    private static final String MESSAGE_TEMPLATE = "业务异常 - {}";


    @ExceptionHandler({ContentNotFoundException.class, TemplateNotFoundException.class})
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ErrorResponse handleNotFound(MailSenderException e) {
        return handleMailSenderException(e);
    }

    public ErrorResponse handleMailSenderException(MailSenderException e) {
        ErrorResponse rslt = new ErrorResponse();
        rslt.setClazz(e.getClass().getName());
        rslt.setError(e.getMessage());
        rslt.getParams().addAll(e.getParams());

        if (log.isDebugEnabled()) {
            log.debug(MESSAGE_TEMPLATE, rslt);
        }
        return rslt;
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ErrorResponse handleInternalServerError(Exception e) {
        log.error("系统异常", e);

        ErrorResponse rslt = new ErrorResponse();
        rslt.setClazz(e.getClass().getName());
        rslt.setError(e.getMessage());
        return rslt;
    }
}
